package com.esun.rabbit2.viewer.mainact.lotteryhallact.sportteryfootballshengfu;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.UserInfo;
import com.esun.model.sportteryfootballshengfu.SportteryFootballShengfuAgainstInfo;
import com.esun.model.sportteryfootballshengfu.SportteryFootballShengfuLotteryInfo;
import com.esun.rabbit2.communicaters.sportteryfootballshengfu.SportteryFootballShengfuAgainstInfoCommunicater;
import com.esun.rabbit2.viewer.LoginAct;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.SportteryBuyLottery;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.SportteryChooseActivity;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.SportteryChooseList;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.SportteryFootballShengfuAgp;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: SportteryFootballShengfuChooseList_test
 * @Description: 胜负彩选队列表页面
 * @author: Liujun liuj@500wan.com
 * @date: 2012-4-19 上午10:04:18
 * 
 */
public class SportteryFootballShengfuChooseList extends SportteryChooseList implements OnClickListener, OnScrollListener {

	private Context context;
	private View view;
	private SportteryBuyLottery buyLotteryPage;

	/** textview */
	private TextView tv_homeName; // 主队名字
	private TextView tv_guestteam; // 客队名字
	private TextView tv_simplegbname; // 联盟名字
	private TextView tv_qihaoName; // 序列号

	/** Button */
	private Button btnClaen; // 清除
	private Button btnSubmit; // 选好了
	private Button btnRefresh; // 刷新
	// private String[] storage_plurl = new String[3];// 字符数组 存放 胜平负 赔率
	private ArrayList<SportteryFootballShengfuAgainstInfo> listInfo;
	// listinfo 里面存的 是 sportteryFootballNoFilterAgainstInfoCommunicater.getAgainstInfoList() 这个对阵信息的数据

	private ListView footballshengfuListViewContent;

	private SportteryFootballShengfuListViewAdapter sportteryFootballShengfuListViewAdapter;

	private SportteryFootballShengfuAgainstInfoCommunicater sportteryFootballShengfuAgainstInfoCommunicater;
	public static Handler handlerChoosePage;

	public static final int RANDOM_CHOOSE_SHENGFUCAI = 101;

	private boolean isUpdateAgainstList = false;

	private RelativeLayout progressdialogRefresh;

	private ArrayList<Hashtable<String, Object>> storecheckvalues;

	// storecheckvalues 里面 存的是tableInListContentNotTitle方法里的值 刚开始初始化的同时 就进行 给值 然后进行全局变量来用
	public SportteryFootballShengfuChooseList(Context context, View view) {
		this.view = view;
		this.context = context;
		init();
		refresh();
		handlerInit();
	}

	/** handler 处理事件 */
	private void handlerInit() {
		handlerChoosePage = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case GETAGAINSTLIST_SUCCEED:
					isUpdateAgainstList = false;
					getAgainstSucceed();
					break;

				case DO_REFRESH:
					refresh();
					break;
				case DO_FINISH:
					((Activity) context).getParent().finish();
					break;

				case DO_CLEAR:
					cleanListView();
					break;

				case DO_BACK_UPDATE:
					storecheckvalues.clear();
					storecheckvalues.addAll(SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getLotterList());
					sportteryFootballShengfuListViewAdapter.notifyDataSetChanged();

					break;

				case GETAGAINSTLIST_FAIL:

					isUpdateAgainstList = false;
					sportteryFootballShengfuListViewAdapter.notifyDataSetChanged();
					progressdialogRefresh.setVisibility(View.INVISIBLE);
					// ViewerUtil.showTipDialog(context, sportteryFootballShengfuAgainstInfoCommunicater.getServerMsg(), false);
					Toast.makeText(context, sportteryFootballShengfuAgainstInfoCommunicater.getServerMsg(), 0).show();
					break;

				case Config.CONNECTION_FAIL:

					sportteryFootballShengfuListViewAdapter.notifyDataSetChanged();
					isUpdateAgainstList = false;
					progressdialogRefresh.setVisibility(View.INVISIBLE);
					// ViewerUtil.showTipDialog(context, Language.STR_CONNECTIONFAIL, false);
					Toast.makeText(context, Language.STR_CONNECTIONFAIL, 0).show();
					break;

				case RANDOM_CHOOSE_SHENGFUCAI:

					storecheckvalues.clear();
					storecheckvalues.addAll(SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getLotterList());
					EDebug.o(this, "摇晃整体完成，开始更新列表");
					sportteryFootballShengfuListViewAdapter.notifyDataSetChanged();
					EDebug.o(this, "更新列表完成");
					break;
				default:
					break;
				}
			}

		};
	}

	/** 得到全部对阵信息成功与否的布尔值 来判断 然后通过 handler 来发布消息 来实现 handler定时的操作 */
	private void threadAgainst() {

		isUpdateAgainstList = true;
		new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					/** 获取全部对阵信息接口 */
					boolean b = sportteryFootballShengfuAgainstInfoCommunicater.isGetInfoSucceed();
					if (b) {
						Message msg = handlerChoosePage.obtainMessage(GETAGAINSTLIST_SUCCEED, null);
						handlerChoosePage.sendMessage(msg);
					} else {
						Message msg = handlerChoosePage.obtainMessage(GETAGAINSTLIST_FAIL, null);
						handlerChoosePage.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handlerChoosePage.obtainMessage(Config.CONNECTION_FAIL, null);
					handlerChoosePage.sendMessage(msg);
				}
			}
		}.start();
	}

	/** 判断 */
	private boolean canCommunicate() {
		boolean b;
		if (!isUpdateAgainstList) {
			b = true;
		} else {
			b = false;
		}
		return b;
	}

	/** 得到对阵信息成功后的数据处理 */
	private void getAgainstSucceed() {
		try {
			progressdialogRefresh.setVisibility(View.INVISIBLE);
		} catch (Exception e) {
			EDebug.o(SportteryFootballShengfuChooseList.this, e.toString());
		}
		listInfo.clear();
		listInfo.addAll(sportteryFootballShengfuAgainstInfoCommunicater.getAgainstInfoList());
		updateStorecheckvalues();
		SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getlistInfo().clear();
		SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getlistInfo().addAll(listInfo);
		SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().setVoteEndTime(sportteryFootballShengfuAgainstInfoCommunicater.getResult().get(Key.KEY_FSENDTIME));
		SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().setExpect(sportteryFootballShengfuAgainstInfoCommunicater.getResult().get(Key.KEY_EXPECT));
		sportteryFootballShengfuListViewAdapter.notifyDataSetChanged();

	}

	public View getView() {
		((SportteryChooseActivity) context).setCurrentPageFlag(0);
		Message msg = SportteryFootballShengfuAgp.handlerSportteryFootballShengfuAgp.obtainMessage(SportteryFootballShengfuAgp.IN_CHOOSE_VIEW, listInfo.size());
		SportteryFootballShengfuAgp.handlerSportteryFootballShengfuAgp.sendMessage(msg);
		return view;
	}

	/** 刷新 */
	private void refresh() {
		if (canCommunicate()) {
			progressdialogRefresh.setVisibility(View.VISIBLE);
			threadAgainst();
		} else {
			EDebug.o(SportteryFootballShengfuChooseList.this, " 通信中..");
		}
	}

	/** 界面下面三个按钮的监听 以及获取对战球队的信息 ，适配器的设置 初始化界面 */
	private void init() {
		EDebug.o(this, "view = " + view.toString());
		btnClaen = (Button) view.findViewById(R.id.sportteryfootballshengfuchooseact_btn_clean);
		btnSubmit = (Button) view.findViewById(R.id.sportteryfootballshengfuchooseact_btn_submit);
		btnRefresh = (Button) view.findViewById(R.id.sportteryfootballshengfuchooseact_btn_refresh);

		btnClaen.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		btnRefresh.setOnClickListener(this);

		listInfo = new ArrayList<SportteryFootballShengfuAgainstInfo>();
		storecheckvalues = new ArrayList<Hashtable<String, Object>>();

		sportteryFootballShengfuAgainstInfoCommunicater = new SportteryFootballShengfuAgainstInfoCommunicater();
		footballshengfuListViewContent = (ListView) view.findViewById(R.id.sportteryfootballshengfuchooseact_listview_content);
		sportteryFootballShengfuListViewAdapter = new SportteryFootballShengfuListViewAdapter(context);
		footballshengfuListViewContent.setAdapter(sportteryFootballShengfuListViewAdapter);
		footballshengfuListViewContent.setOnScrollListener(this);

		progressdialogRefresh = (RelativeLayout) view.findViewById(R.id.sportteryfootballshengfu_relative_progress);
		SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getAllLeagueList().clear();
	}

	/** Storecheckvalues 里面 存的是下面的东西 刚开始初始化的同时 就进行 给值 然后进行全局变量来用 最后放到 SportteryFootballShengfuLotteryInfo 类与类之间 值共享 */

	private void updateStorecheckvalues() {
		if (listInfo.size() > 0) {
			storecheckvalues.clear();
			for (int i = 0; i < listInfo.size(); i++) {
				storecheckvalues.add(tableInListContentNotTitle(i));
			}
		} else {
			storecheckvalues.clear();
		}
	}

	/** 固定的hashtable 存储一些固定的键值对 */
	private Hashtable<String, Object> tableInListContentNotTitle(int position) {
		Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
		hashtable.put(INFO, listInfo.get(position));
		hashtable.put(IS_TITLE, false);
		hashtable.put(W, false);
		hashtable.put(D, false);
		hashtable.put(L, false);
		hashtable.put(IS_ACTIVE, false);
		return hashtable;
	}

	/** 用于点击事件的监听 */
	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.sportteryfootballshengfuchooseact_btn_refresh:
			Message msg = handlerChoosePage.obtainMessage(DO_REFRESH, null);
			handlerChoosePage.sendMessage(msg);
			break;

		case R.id.sportteryfootballshengfuchooseact_btn_clean:
			cleanListView();
			break;

		case R.id.sportteryfootballshengfuchooseact_btn_submit:
			if (getActiveTeamCount() < getLimitEventCount()) {
				ViewerUtil.showTipDialog(context, "最少选择" + getLimitEventCount() + "场比赛", false);
			} else if (UserInfo.getUserInfo().getUserSession().length() < 3) {
				Intent intent = new Intent();
				intent.setClass(context, LoginAct.class);
				((Activity) context).startActivity(intent);
			} else {
				SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getLotterList().clear();
				SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getLotterList().addAll(storecheckvalues);
				((Activity) context).setContentView(buyLotteryPage.getView());
			}
			break;

		default:
			break;
		}
	}

	// }
	/** 得到最低选场场次 */
	private int getLimitEventCount() {
		int i = 14;
		return i;
	}

	/** 用于清除事件 */
	private void cleanListView() {

		for (int i = 0; i < storecheckvalues.size(); i++) {
			if (!(Boolean) storecheckvalues.get(i).get(IS_TITLE)) {
				storecheckvalues.get(i).put(W, false);
				storecheckvalues.get(i).put(D, false);
				storecheckvalues.get(i).put(L, false);
				storecheckvalues.get(i).put(IS_ACTIVE, false);
				storecheckvalues.get(i).put(IS_DAN, false);
			}
		}
		sportteryFootballShengfuListViewAdapter.notifyDataSetChanged();
	}

	/** 记录checkbox 点击事件的值 用于一直显示 同时判断场次是否选多了 */
	private void updateTableLottery(int position, boolean w, boolean d, boolean l, CheckBox cbx, String key, SportteryFootballShengfuAgainstInfo sportteryFootballAgainstInfo) {
		boolean isChecked = false;
		if (key.equals(W)) {
			isChecked = w;
		} else if (key.equals(D)) {
			isChecked = d;
		} else if (key.equals(L)) {
			isChecked = l;
		} else {
			EDebug.o(SportteryFootballShengfuChooseList.this, "sun your sister ...");
		}
		storecheckvalues.get(position).put(key, isChecked);
		storecheckvalues.get(position).put(IS_ACTIVE, true);
		storecheckvalues.get(position).put(INFO, listInfo.get(position));
		if (!w && !d && !l) {
			storecheckvalues.get(position).put(IS_ACTIVE, false);
		}
	}

	private int getActiveTeamCount() {
		int activeTeamCount = 0;
		for (int i = 0; i < storecheckvalues.size(); i++) {
			if ((Boolean) storecheckvalues.get(i).get("is_active")) {
				activeTeamCount++;
			}
		}
		return activeTeamCount;
	}

	/** listview适配器 用于显示界面 */
	class SportteryFootballShengfuListViewAdapter extends BaseAdapter {
		private LayoutInflater listInflater;

		public SportteryFootballShengfuListViewAdapter(Context context) {

			this.listInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {

			return listInfo.size();

		}

		@Override
		public Object getItem(int position) {
			return listInfo.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = listInflater.inflate(R.layout.sportteryfootballshengfu_choose_item, null);
			}
			final SportteryFootballShengfuAgainstInfo sportteryFootballAgainstInfo = (SportteryFootballShengfuAgainstInfo) listInfo.get(position);
			// 从sportteryFootballAgainstInfo 这里获得信息 来显示到子菜单中去
			tv_homeName = (TextView) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_tv_homeName);
			tv_homeName.setText(sportteryFootballAgainstInfo.getHometeam());

			tv_guestteam = (TextView) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_tv_visiterName);
			tv_guestteam.setText(sportteryFootballAgainstInfo.getGuestteam());

			tv_simplegbname = (TextView) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_tv_leagueName);
			tv_simplegbname.setText(sportteryFootballAgainstInfo.getSimplegbname());

			// 下面为设置本布局前面的排列号 由于接口没有返回值 所以利用position值加1来显示
			tv_qihaoName = (TextView) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_tv_qihaoName);
			tv_qihaoName.setText("" + (position + 1) + "");

			// String plurl = sportteryFootballAgainstInfo.getPlurl();
			// // 判断返回的赔率是否为空，防止返回空时程序崩溃
			// if (plurl == null || plurl.equals(Config.NULLMARK)) {
			// for (int i = 0; i < 3; i++) {
			// storage_plurl[i] = "--";
			// }
			// } else {
			// storage_plurl = plurl.split(",");
			// int bb_length = storage_plurl.length;
			// if (bb_length < 3) {
			// for (int i = bb_length; i < 3; i++) {
			// storage_plurl[i] = "--";
			// }
			// }
			// }

			final CheckBox cbxW = (CheckBox) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_cbx_W);
			final CheckBox cbxD = (CheckBox) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_cbx_D);
			final CheckBox cbxL = (CheckBox) convertView.findViewById(R.id.sportteryfootballshengfuchooseitem_cbx_L);

			final int position_ = position;
			OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					switch (buttonView.getId()) {
					case R.id.sportteryfootballshengfuchooseitem_cbx_W:
						updateTableLottery(position_, isChecked, cbxD.isChecked(), cbxL.isChecked(), cbxW, W, sportteryFootballAgainstInfo);

						if (isChecked) {

							SpannableString spannableString_cbxW = getSpannableString_white(buttonView.getText().toString());
							cbxW.setText(spannableString_cbxW);
						} else {

							SpannableString spannableString_cbxW = getSpannableString_black(buttonView.getText().toString());
							cbxW.setText(spannableString_cbxW);

						}
						break;

					case R.id.sportteryfootballshengfuchooseitem_cbx_D:
						updateTableLottery(position_, cbxW.isChecked(), isChecked, cbxL.isChecked(), cbxD, D, sportteryFootballAgainstInfo);

						if (isChecked) {

							SpannableString spannableString_cbxD = getSpannableString_white(buttonView.getText().toString());
							cbxD.setText(spannableString_cbxD);

						} else {

							SpannableString spannableString_cbxD = getSpannableString_black(buttonView.getText().toString());
							cbxD.setText(spannableString_cbxD);

						}
						break;

					case R.id.sportteryfootballshengfuchooseitem_cbx_L:
						updateTableLottery(position_, cbxW.isChecked(), cbxD.isChecked(), isChecked, cbxL, L, sportteryFootballAgainstInfo);

						if (isChecked) {

							SpannableString spannableString_cbxL = getSpannableString_white(buttonView.getText().toString());
							cbxL.setText(spannableString_cbxL);

						} else {

							SpannableString spannableString_cbxL = getSpannableString_black(buttonView.getText().toString());
							cbxL.setText(spannableString_cbxL);

						}
						break;

					default:
						break;
					}

				}
			};
			cbxW.setOnCheckedChangeListener(onCheckedChangeListener);
			cbxD.setOnCheckedChangeListener(onCheckedChangeListener);
			cbxL.setOnCheckedChangeListener(onCheckedChangeListener);
			cbxW.setChecked((Boolean) storecheckvalues.get(position).get(W));
			cbxD.setChecked((Boolean) storecheckvalues.get(position).get(D));
			cbxL.setChecked((Boolean) storecheckvalues.get(position).get(L));

			if ((Boolean) storecheckvalues.get(position).get(W)) {

				SpannableString spannableString_cbxW = getSpannableString_white(Config.NUM3);
				cbxW.setText(spannableString_cbxW);

			} else {

				SpannableString spannableString_cbxW = getSpannableString_black(Config.NUM3);
				cbxW.setText(spannableString_cbxW);

			}
			if ((Boolean) storecheckvalues.get(position).get(D)) {

				SpannableString spannableString_cbxD = getSpannableString_white(Config.NUM1);
				cbxD.setText(spannableString_cbxD);

			} else {

				SpannableString spannableString_cbxD = getSpannableString_black(Config.NUM1);
				cbxD.setText(spannableString_cbxD);

			}
			if ((Boolean) storecheckvalues.get(position).get(L)) {

				SpannableString spannableString_cbxL = getSpannableString_white(Config.NUM0);
				cbxL.setText(spannableString_cbxL);

			} else {

				SpannableString spannableString_cbxL = getSpannableString_black(Config.NUM0);
				cbxL.setText(spannableString_cbxL);

			}

			return convertView;
		}

	}

	/** 设置文本内容特定位置的字体颜色 */
	private SpannableString getSpannableString_white(String source) {
		SpannableString spannableString_cb = new SpannableString(source);
		spannableString_cb.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.white)), 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		return spannableString_cb;
	}

	/** 设置文本内容特定位置的字体颜色 */
	private SpannableString getSpannableString_black(String source) {
		SpannableString spannableString_cb = new SpannableString(source);
		spannableString_cb.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.solid_black)), 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		return spannableString_cb;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void setSportteryBuyLotteryPage(SportteryBuyLottery buyLotteryPage) {
		this.buyLotteryPage = buyLotteryPage;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub

	}
}
